'''
数据处理层：实现连接数据库，写数据库，读数据库
'''
import pymysql

host='localhost'
port=3308
user='root'
password='123456'
database='cz'
charset='utf8'

# 连接数据库
def get_conn():
    db = pymysql.Connect(host=host, port=port, user=user, password=password, database=database, charset=charset)
    # print('数据库已链接')
    return db

# 查询
def read_data(sql):
    db=get_conn()
    cursor=db.cursor()
    data=None
    try:
        cursor.execute(sql)
        data=cursor.fetchall()
        # print('已查询')
    except Exception as e:
        print(e)
    cursor.close()
    db.close()
    return data
def write_data(sql):
    db=get_conn()
    cursor=db.cursor()
    rows=0
    try:
        rows=cursor.execute(sql)
        db.commit()
        # print('已读取')
    except Exception as e:
        print(e)
    cursor.close()
    db.close()
    return rows
if __name__ == '__main__':
    # # 测试一下get_conn
    # print(get_conn())
    # # 测试一下read_data
    # sql="select * from tb3"
    # data=read_data(sql)
    # print(data)
    # 测试一下write_data
    sql="insert into tb3 values(null,'cz','15236652368')"
    print(write_data(sql))
